/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.atm.user.model;

import com.atm.user.dao.ConnectDatabase;
import com.atm.user.entities.ChuyenKhoan;
import com.atm.user.entities.GuiTien;
import com.atm.user.entities.RutTien;
import com.atm.user.entities.TaiKhoan;
import com.atm.user.gui.ATMUserGUI;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.atm.user.language.Language;
import codeblue.project.MD5Encode;
import com.c1202m.dao.QuyDinhDAO;
import com.c1202m.gui.CustomMessageDialog;
import com.c1202m.gui.Help;
import static com.c1202m.gui.Help.guiToiThieu;
import static com.c1202m.gui.Help.rutToiDaGD;
import static com.c1202m.gui.Help.rutToiDaN;
import static com.c1202m.gui.Help.rutToiThieuGD;
import static com.c1202m.gui.Help.soDuToiThieu;
import static com.c1202m.gui.Help.soLanRutToiDaN;
import com.c1202m.hibernate.entities.QuyDinh;
import java.io.File;

/**
 *
 * @author TuanNguyen
 */
public class ATMUserControl {

    private ATMUserGUI gui;
    private ConnectDatabase db;
    private TaiKhoan user, transferUser;
    private int count_type_incorrect_PIN;//đếm số lần nhập sai PIN,tối đa 3 lần
    private String newPIN, cashDeposit, cashWithDraw, fundTransfer;
    private float sodumoi;
    private File file = null;

    public ATMUserControl(ATMUserGUI gui) {
        this.gui = gui;
        this.gui.addProcessListener(new ProcessListener());
        this.gui.addKeyPressListener(new PressEnterListener());
        db = new ConnectDatabase();
        count_type_incorrect_PIN = 0;

        file = new File("quydinh.txt");
        boolean isExists = file.exists();
        if (isExists) {
            QuyDinh quyDinh = QuyDinhDAO.docFile(file.getName());
            soDuToiThieu = quyDinh.getGuiToiThieu();
            guiToiThieu = quyDinh.getGuiToiThieu();
            rutToiThieuGD = quyDinh.getRutToiThieuGD();
            rutToiDaGD = quyDinh.getRutToiDaGD();
            rutToiDaN = quyDinh.getRutToiDaN();
            soLanRutToiDaN = quyDinh.getSoLanRutToiDaN();
        } else {
            new CustomMessageDialog(null, true, "Warning!", "không tìm thấy file quydinh.txt", CustomMessageDialog.MESSAGE);
            return;
        }
    }

    class ProcessListener implements ActionListener {//sử lí sự kiện click vào 1 trong 8 button

        @Override
        public void actionPerformed(ActionEvent e) {
            int screenType = gui.getScreenType();
            switch (screenType) {
                case 0:
                    if (e.getSource() == gui.getBt7()) {
                        Language.getInstance().setType(0);//chọn tiếng việt
                    } else if (e.getSource() == gui.getBt8()) {
                        Language.getInstance().setType(1);//chọn english
                    }
                    gui.setScreen(1);
                    break;
                case 1:
                    if (e.getSource() == gui.getBt4()) {
                        gui.setScreen(0);
                    }
                    break;
                case 2:
                    if (e.getSource() == gui.getBt4()) {
                        gui.setScreen(0);
                    }
                    break;
                case 3:
                    if (e.getSource() == gui.getBt1()) {
                        gui.setScreen(4);
                    } else if (e.getSource() == gui.getBt2()) {
                        gui.setScreen(18);
                        String msg = Language.getInstance().getHello() + " " + user.getChuTK();
                        gui.setMessageTop(msg);
                        
                        float tong_tien_gui = db.getTongTienGui(user);
                        int so_lan_gui = db.getSoLanGui(user);

                        float tong_tien_rut = db.getRutToiDa1Ngay(user);
                        int so_lan_rut = db.getSoLanRutToiDa1Ngay(user);
                        
                        String msg2 = "<html>" + Language.getInstance().getSoDu() + " " + user.getSoduTK() + " VND"
                                + "<br><br>" + Language.getInstance().getSoLanGui() + " " + so_lan_gui
                                + "<br>" + Language.getInstance().getTongTienGui() + " " + tong_tien_gui + " VND"
                                + "<br>" + Language.getInstance().getSoLanRut() + " " + so_lan_rut
                                + "<br>" + Language.getInstance().getTongTienRut() + " " + tong_tien_rut + " VND"
                                + "<html/>";
                        gui.setInquiry(msg2);
                        
                    } else if (e.getSource() == gui.getBt3()) {
                        gui.setScreen(17);
                    } else if (e.getSource() == gui.getBt4()) {
                        gui.setScreen(8);
                    } else if (e.getSource() == gui.getBt6()) {
                        gui.setScreen(9);
                    } else if (e.getSource() == gui.getBt5()) {
                        gui.setScreen(12);
                    } else if (e.getSource() == gui.getBt7()) {
                        gui.setScreen(14);
                    } else if (e.getSource() == gui.getBt8()) {
                        gui.setScreen(18);
                        String msg = Language.getInstance().getSoDu() + " " + user.getSoduTK() + " VND";
                        gui.setMessageTop(msg);

                        ArrayList<GuiTien> listTienGuiTrongNgay = db.getListTienGuiTrongNgay(user);
                        ArrayList<RutTien> listTienRutTrongNgay = db.getListTienRutTrongNgay(user);
                        ArrayList<ChuyenKhoan> listTienChuyenTrongNgay = db.getListTienChuyenTrongNgay(user);

                        String type = "<html>" + Language.getInstance().getTypeS()
                                + "<br><br>";
                        String amount = "<html>" + Language.getInstance().getAmount()
                                + "<br><br>";
                        String time = "<html>" + Language.getInstance().getTimeS()
                                + "<br><br>";
                        for (GuiTien i : listTienGuiTrongNgay) {
                            type += Language.getInstance().getFuntion_cashDeposit() + "<br>";
                            amount += i.getSo_tien_gui() + "<br>";
                            time += i.getSoTk() + "<br>";
                        }
                        for (RutTien i : listTienRutTrongNgay) {
                            type += Language.getInstance().getFuntion_cashWithDraw() + "<br>";
                            amount += i.getSo_tien_rut() + "<br>";
                            time += i.getSoTk() + "<br>";
                        }
                        for (ChuyenKhoan i : listTienChuyenTrongNgay) {
                            type += Language.getInstance().getFuntion_fundTransfer() + "<br>";
                            amount += i.getSo_tien_gui() + "<br>";
                            time += i.getSoTk_gui() + "<br>";
                        }

                        type += "<html/>";
                        amount += "<html/>";
                        time += "<html/>";

                        gui.setType(type);
                        gui.setAmount(amount);
                        gui.setTime(time);
                    }
                    break;
                case 4:
                    if (e.getSource() == gui.getBt4()) {
                        gui.setScreen(3);
                    }
                    break;
                case 5:
                    if (e.getSource() == gui.getBt4()) {
                        gui.setScreen(3);
                    }
                    break;
                case 6:
                    if (e.getSource() == gui.getBt4()) {
                        gui.setScreen(3);
                    }
                    break;
                case 8:
                    if (e.getSource() == gui.getBt7()) {
                        gui.setScreen(7);

                        String msg = "<html>" + Language.getInstance().getThankyou() + " " + user.getChuTK() + "<br>" + Language.getInstance().getSeeyouagain() + "</html>";
                        gui.setMessageTop(msg);
                        threadRedirect(0);
                    } else if (e.getSource() == gui.getBt8()) {
                        gui.setScreen(3);
                    }
                    break;
                case 9:
                    if (e.getSource() == gui.getBt4()) {
                        gui.setScreen(3);
                    }
                    break;
                case 10:
                    if (e.getSource() == gui.getBt7()) {
                        gui.setScreen(11);

                        if (checkBoiCua50000(Integer.parseInt(cashDeposit)) && checkGuiToiThieu(Integer.parseInt(cashDeposit))) {
                            System.out.println("Số dư=" + user.getSoduTK());
                            sodumoi = Float.parseFloat(user.getSoduTK()) - Integer.parseInt(cashDeposit);
                            System.out.println("Số dư mới=" + sodumoi);

                            user.setSoduTK(String.valueOf(sodumoi));
                            db.updateUser(user);

                            GuiTien gt = new GuiTien(user.getSoTK(), String.valueOf(cashDeposit), null);
                            db.insertGuiTien(gt);
                            threadTransaction(7, true, null);
                        } else {
                            String mes = Language.getInstance().getAccNotEnoughMoney();
                            threadTransaction(7, false, mes);
                        }

                    } else if (e.getSource() == gui.getBt8()) {
                        gui.setScreen(7);
                        String msg = Language.getInstance().getTransactionDenied();
                        gui.setMessageTop(msg);
                        threadRedirect(3);
                    }
                    break;
                case 12:
                    if (e.getSource() == gui.getBt4()) {
                        gui.setScreen(3);
                    } else if (e.getSource() == gui.getBt1()) {
                        gui.setScreen(11);
                        rutTien(50000);
                    } else if (e.getSource() == gui.getBt2()) {
                        gui.setScreen(11);
                        rutTien(100000);
                    } else if (e.getSource() == gui.getBt3()) {
                        gui.setScreen(11);
                        rutTien(200000);
                    } else if (e.getSource() == gui.getBt5()) {
                        gui.setScreen(11);
                        rutTien(500000);
                    } else if (e.getSource() == gui.getBt6()) {
                        gui.setScreen(11);
                        rutTien(1000000);
                    } else if (e.getSource() == gui.getBt7()) {
                        gui.setScreen(11);
                        rutTien(2000000);
                    } else if (e.getSource() == gui.getBt8()) {
                        gui.setScreen(13);
                    }

                    break;
                case 13:
                    if (e.getSource() == gui.getBt4()) {
                        gui.setScreen(3);
                    }
                    break;
                case 14:
                    if (e.getSource() == gui.getBt4()) {
                        gui.setScreen(3);
                    }
                    break;
                case 15:
                    if (e.getSource() == gui.getBt4()) {
                        gui.setScreen(3);
                    }
                    break;
                case 16:
                    if (e.getSource() == gui.getBt7()) {
                        gui.setScreen(11);

                        sodumoi = Float.parseFloat(user.getSoduTK()) - Float.parseFloat(fundTransfer);
                        user.setSoduTK(String.valueOf(sodumoi));
                        db.updateUser(user);

                        float sodu_tranferUser = Float.parseFloat(transferUser.getSoduTK());
                        sodu_tranferUser += Float.parseFloat(fundTransfer);
                        transferUser.setSoduTK(String.valueOf(sodu_tranferUser));
                        db.updateUser(transferUser);

                        ChuyenKhoan ck = new ChuyenKhoan(user.getSoTK(), transferUser.getSoTK(), fundTransfer, null);
                        db.insertChuyenTien(ck);
                        threadTransaction(7, true, null);
                    } else if (e.getSource() == gui.getBt8()) {
                        threadTransaction(7, false, null);
                    }
                    break;
                case 17:
                    if (e.getSource() == gui.getBt4()) {
                        gui.setScreen(3);
                    }
                    break;
                case 18:
                    if (e.getSource() == gui.getBt4()) {
                        gui.setScreen(3);
                    }
                    break;
            }

        }
    }

    class PressEnterListener implements KeyListener {//lớp xử lí cho sự kiện ấn nút enter

        @Override
        public void keyPressed(KeyEvent e) {

            int screenType = gui.getScreenType();

            if (screenType == 1 && e.getKeyCode() == KeyEvent.VK_ENTER) {
                String accNo = gui.getTxtAccNo().getText().trim();
                boolean check = db.checkAccount(accNo);
                System.out.println("check=" + check);
                if (check) {
                    user = db.getUser(accNo);
                    gui.setUsername(user.getChuTK());
                    gui.setScreen(2);
                } else {
                    gui.setScreen(1);
                    String msg = "<html>" + Language.getInstance().getErroTypeAccNo() + "<br>" + Language.getInstance().getTryAgain() + "</html>";
                    gui.setMessageMid(msg);
                }
            } else if (screenType == 2 && e.getKeyCode() == KeyEvent.VK_ENTER) {
                String accPIN = MD5Encode.encode(new String(gui.getPfPIN().getPassword()));
                if (count_type_incorrect_PIN == 3) {
                } else if (accPIN.equals(user.getPIN())) {
                    gui.setScreen(3);//chuyển sang màn hình gồm các chức năng chính
                } else {
                    count_type_incorrect_PIN++;//đếm số lần nhập pin sai
                    gui.setScreen(2);
                    String msg = "<html>" + Language.getInstance().getErroTypeAccPIN()
                            + "<br>" + Language.getInstance().getTryAgain()
                            + " " + String.valueOf(3 - count_type_incorrect_PIN)
                            + " " + Language.getInstance().getTimeLeft()
                            + "</html>";
                    gui.setMessageMid(msg);
                }
            } else if (screenType == 4 && e.getKeyCode() == KeyEvent.VK_ENTER) {
                String oldPIN = MD5Encode.encode(new String(gui.getPfPIN().getPassword()));
                if (oldPIN.equals(user.getPIN())) {
                    gui.setScreen(5);
                } else {
                    gui.setScreen(7);
                    gui.setMessageTop(Language.getInstance().getErroTypeAccPIN());
                    threadRedirect(3);
                }
            } else if (screenType == 5 && e.getKeyCode() == KeyEvent.VK_ENTER) {
                newPIN = MD5Encode.encode(new String(gui.getPfPIN().getPassword()));
                gui.setScreen(6);
            } else if (screenType == 6 && e.getKeyCode() == KeyEvent.VK_ENTER) {
                String reNewPIN = MD5Encode.encode(new String(gui.getPfPIN().getPassword()));
                if (reNewPIN.equals(newPIN)) {
                    gui.setScreen(7);
                    user.setPIN(newPIN);
                    db.updateUser(user);

                    gui.setMessageTop(Language.getInstance().getPinChanged());
                    threadRedirect(3);
                } else {
                    gui.setScreen(7);
                    gui.setMessageTop(Language.getInstance().getErroTypeAccPIN());
                    threadRedirect(3);
                }
            } else if (screenType == 9 && e.getKeyCode() == KeyEvent.VK_ENTER) {

                cashDeposit = gui.getPfCash().getText().trim();
                System.out.println("cash deposit=" + cashDeposit);
                if (checkGuiToiThieu(Integer.parseInt(cashDeposit))) {
                    gui.setScreen(10);
                    String msg = Language.getInstance().getDepositConfirm() + " " + cashDeposit + " VND?";
                    gui.setMessageTop(msg);
                } else {
                    String msg = Language.getInstance().getCastDepositCondition1();
                    gui.setScreen(9);
                    gui.setMessageMid(msg);
                }
            } else if (screenType == 13 && e.getKeyCode() == KeyEvent.VK_ENTER) {//nhập sô tiền để rút

                cashWithDraw = gui.getPfCash().getText().trim();
                System.out.println("cash withdraw=" + cashWithDraw);
                gui.setScreen(11);
                rutTien2(Float.parseFloat(cashWithDraw));
            } else if (screenType == 14 && e.getKeyCode() == KeyEvent.VK_ENTER) {
                String accNo = gui.getTxtAccNo().getText().trim();
                boolean check = db.checkAccount(accNo);
                System.out.println("check=" + check);
                if (check) {
                    transferUser = db.getUser(accNo);
                    gui.setScreen(15);
                } else {
                    gui.setScreen(14);
                    String msg = "<html>" + Language.getInstance().getErroTypeAccNo() + "<br>" + Language.getInstance().getTryAgain() + "</html>";
                    gui.setMessageMid(msg);
                }
            } else if (screenType == 15 && e.getKeyCode() == KeyEvent.VK_ENTER) {
                fundTransfer = gui.getPfCash().getText().trim();
                System.out.println("fund transfer=" + fundTransfer);

                float tienChuyen = Float.parseFloat(fundTransfer);
                if (checkBoiCua50000(tienChuyen) && checkSoDuToiThieu(tienChuyen)) {
                    gui.setScreen(16);
                    String msg = "<html>" + Language.getInstance().getXacNhanChuyenTien() + "<br>" + transferUser.getChuTK() + "?<html/>";
                    gui.setMessageTop(msg);
                } else {
                    gui.setScreen(15);
                }


            }
        }

        @Override
        public void keyTyped(KeyEvent e) {
        }

        @Override
        public void keyReleased(KeyEvent e) {
        }
    }

    public void threadRedirect(final int screenTarget) {// chuyển hướng trong 3s
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 5; i > 0; i--) {
                    String mes = Language.getInstance().getRedirectIn() + " " + i + " s";
                    gui.setMessageMid(mes);
                    try {
                        new Thread().sleep(1000);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(ATMUserControl.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                gui.setScreen(screenTarget);
            }
        });
        t.start();
    }

    public void threadTransaction(final int screenTarget, final boolean success, final String mes) {//success=true :thành công,false=từ chối
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i < 101; i++) {
                    gui.getPbTransaction().setValue(i);
                    try {
                        new Thread().sleep(30);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(ATMUserControl.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                gui.setScreen(screenTarget);
                String msg = null;
                if (success) {
                    msg = Language.getInstance().getTransactionComplete();
                } else {
                    msg = "<html>" + mes + "<br>" + Language.getInstance().getTransactionDenied() + "</html>";
                }
                gui.setMessageTop(msg);
                threadRedirect(3);
            }
        });
        t.start();
    }

    public boolean checkSoDuToiThieu(float tien) {
        if (Float.parseFloat(user.getSoduTK()) - tien >= Help.soDuToiThieu) {
            return true;
        }
        return false;
    }

    public boolean checkBoiCua50000(float tien) {
        if (tien % 50000 == 0) {
            return true;
        }
        return false;
    }

    public boolean checkGuiToiThieu(float tien) {
        if (tien >= Help.guiToiThieu) {
            return true;
        }
        return false;
    }

    public boolean checkRutToiThieu1GiaoDich(float tien) {
        if (tien >= Help.rutToiThieuGD) {
            return true;
        }
        return false;
    }

    public boolean checkRutToiDa1GiaoDich(float tien) {
        if (tien <= Help.rutToiDaGD) {
            return true;
        }
        return false;
    }

    public boolean checkRutToiDa1Ngay(float tien) {
        float tong_da_rut = db.getRutToiDa1Ngay(user);
        if (tong_da_rut + tien <= Help.rutToiDaN) {
            return true;
        } else {
            return false;
        }
    }

    public boolean checkSoLanRutToiDa1Ngay() {
        int solanrut = db.getSoLanRutToiDa1Ngay(user);
        if (solanrut <= Help.soLanRutToiDaN) {
            return true;
        } else {
            return false;
        }
    }

    public void rutTien(float tienrut) {
        if (checkSoDuToiThieu(tienrut)
                && checkRutToiDa1GiaoDich(tienrut)
                && checkBoiCua50000(tienrut)
                && checkRutToiDa1Ngay(tienrut)
                && checkRutToiThieu1GiaoDich(tienrut)
                && checkSoLanRutToiDa1Ngay()) {

            System.out.println("check rut tien ok");

            sodumoi = Float.parseFloat(user.getSoduTK()) - tienrut;
            user.setSoduTK(String.valueOf(sodumoi));
            db.updateUser(user);

            RutTien rt = new RutTien(user.getSoTK(), String.valueOf(tienrut), null);
            db.insertRutTien(rt);

            threadTransaction(7, true, null);
        } else {
            String msg = "<html>" + Language.getInstance().getDieuKienRutTien1()
                    + "<br>" + Language.getInstance().getDieuKienRutTien2()
                    + "<br>" + Language.getInstance().getDieuKienRutTien3()
                    + "<html/>";
            threadTransaction(7, false, msg);
        }
    }

    public void rutTien2(float tienrut) {
        if (checkSoDuToiThieu(tienrut)
                && checkRutToiDa1GiaoDich(tienrut)
                && checkBoiCua50000(tienrut)
                && checkRutToiDa1Ngay(tienrut)
                && checkRutToiThieu1GiaoDich(tienrut)
                && checkSoLanRutToiDa1Ngay()) {

            System.out.println("check rut tien ok");

            sodumoi = Float.parseFloat(user.getSoduTK()) - tienrut;
            user.setSoduTK(String.valueOf(sodumoi));
            db.updateUser(user);

            RutTien rt = new RutTien(user.getSoTK(), String.valueOf(tienrut), null);
            db.insertRutTien(rt);

            threadTransaction(7, true, null);
        } else {
            String msg = "<html>" + Language.getInstance().getDieuKienRutTien1()
                    + "<br>" + Language.getInstance().getDieuKienRutTien2()
                    + "<br>" + Language.getInstance().getDieuKienRutTien3()
                    + "<html/>";
            gui.setScreen(13);
            gui.setMessageMid(msg);
        }
    }
}
